package query;


import client.ClientFactory;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public abstract class Search {
    protected static Logger log = LoggerFactory.getLogger(Search.class);
    protected static String index;
    protected static String type;
    protected static QueryBuilder queryBuilder;
    protected static String[] fetchSource;

    protected static SearchResponse createResponse(String aminer, String s, QueryBuilder queryBuilder, String[] fetchSource) {
        SearchResponse searchResponse = ClientFactory.getClient().prepareSearch(index)
                .setTypes(type)
                .setQuery(Search.queryBuilder)
                .setFetchSource(Search.fetchSource, null)
                .setScroll(new TimeValue(100, TimeUnit.MINUTES))
                .setSize(100)
                .get();
        return searchResponse;
    }

    protected static List<SearchHit> searchByScrollId(SearchResponse searchResponse) {
        String id = searchResponse.getScrollId();
        List<SearchHit> searchHitList = new ArrayList<>();
        SearchResponse response;
        SearchHit[] searchHits;
        while (true) {
            response = ClientFactory.getClient().prepareSearchScroll(id)
                    .setScroll(new TimeValue(100, TimeUnit.MINUTES))
                    .get();
            searchHits = response.getHits().getHits();
            if (searchHits.length == 0) {
                break;
            }
            log.info(searchHits.length+" @@ScrollId:" + id);
            searchHitList.addAll(Arrays.asList(searchHits));
        }
        return searchHitList;
    }

    public List<SearchHit> query(SearchResponse response){
        List<SearchHit> result = new ArrayList<>();
        SearchHit[] searchHits = response.getHits().getHits();
        result.addAll(Arrays.asList(searchHits));
        List<SearchHit> searchHitList = searchByScrollId(response);
        result.addAll(searchHitList);
        return result;
    }

    public abstract List<SearchHit> query(String s);


}
